package com.thermometry

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.hardware.usb.UsbManager
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import cn.wch.lib.ch34xMultiDriver
import cn.wch.lib.ch34xMultiManager
import com.faceidentify.R
import com.facerecognition.MainActivity
import com.temHu.MyApp
import kotlinx.android.synthetic.main.activity_therm2.*
import java.io.IOException


class ThermActivity : AppCompatActivity() {
    companion object {
        const val writeString = "40 01 01 40 0D"
        const val TAG = "cn.wch.wchusbdriver"
        const val ACTION_USB_PERMISSION = "cn.wch.wchusbdriver.USB_PERMISSION"
    }

    private var isOpen = false
    private var handler: Handler? = null
    lateinit var writeBuffer: ByteArray
    lateinit var readBuffer: ByteArray
    private val data: Byte = 0
    private var flow: kotlin.Byte = 0
    private var parity: kotlin.Byte = 0
    private val stop: Byte = 1
    var isConfiged = false
    private var tem: Double? = null
    private var thread: writeThread? = null
    private var manager: UsbManager? = null
    private var mediaPlayer: MediaPlayer? = null
    private var uri: Uri? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_therm2)
        initView()
    }

    private fun initView() {
        mediaPlayer = MediaPlayer()
        mediaPlayer!!.setOnCompletionListener {
            isConfiged=false
            isOpen=false
            Thread.sleep(2000)
            startActivity(Intent(this@ThermActivity, MainActivity::class.java))
        }
        manager = getSystemService(Context.USB_SERVICE) as UsbManager
        MyApp.ch34xmag1 = ch34xMultiManager(applicationContext, manager)
        if (!UsbFeatureSupported()) // 是否支持USB HOST
        {
            val dialog: Dialog = AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("设备不支持USB HOST")
                    .setPositiveButton("确定",
                            DialogInterface.OnClickListener { arg0, arg1 -> System.exit(0) }).create()
            dialog.setCanceledOnTouchOutside(false)
            dialog.show()
        }
        writeBuffer = ByteArray(512)
        readBuffer = ByteArray(512)
        isOpen = false
        Them_back.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                isConfiged = false
                isOpen = false
                startActivity(Intent(this@ThermActivity, MainActivity::class.java))
            }
        })
        Them_showTem.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                open()
                if (isOpen) {
                    config()
                    if (isConfiged) {
                        thread = writeThread()
                        thread!!.start()
                    }
                }
            }
        })
        handler = object : Handler() {
            @SuppressLint("HandlerLeak")
            override fun handleMessage(msg: Message) {
                when (msg.what) {
                    0 -> {
                        tem = msg.obj.toString().toDouble()
                        Log.d("TAG", tem.toString() + "摄氏度")
                        Them_text.setText(tem.toString() + "℃")
                        startVoice()
                    }
                }
            }
        }
    }

    //打开设备
    fun open() {
        var mRet = 0
        if (!isOpen) {
            if (MyApp.ch34xmag1 == null) {
                MyApp.ch34xmag1 = ch34xMultiManager(applicationContext, manager)
            }
            Toast.makeText(this, "ch34xmag1:" + MyApp.ch34xmag1!!.usbDeviceList.size, Toast.LENGTH_SHORT).show()
            if (MyApp.ch34xmag1!!.usbDeviceList.size == 0) {
                return
            }
            for (i in MyApp.ch34xmag1!!.usbDeviceList.indices) {
                Log.d("ch34xmag1", "Open" + MyApp.ch34xmag1!!.usbDeviceList[i].deviceName)
                if (!MyApp.ch34xmag1!!.OpenUsbDevice(MyApp.ch34xmag1!!.usbDeviceList[i])) {
                    mRet++
                }
            }
            if (mRet != 0) {
                MyApp.ch34xmag1 = null
                return
            }
            isOpen = true
            Log.d("ch34xmag1", "readthread start")
            readthread().start()
        } else {
            isOpen = false //退出readthread
            MyApp.ch34xmag1!!.CloseAll() //unregisterBroadcast
            MyApp.ch34xmag1 = null
        }
    }

    //配置设备
    fun config() {
        if (!isOpen) {
            Toast.makeText(this, "Not Open", Toast.LENGTH_SHORT).show()
        }
        for (i in MyApp.ch34xmag1!!.ch34xDriverList.indices) {
            isConfiged = if (MyApp.ch34xmag1!!.ch34xDriverList[i].SetConfig(9600, data, stop, parity, flow)) {
                Toast.makeText(this, "Config Success", Toast.LENGTH_SHORT).show()
                true
            } else {
                false
            }
        }
    }

    inner private class readthread : Thread() {
        override fun run() {
            val buffer = ByteArray(4096)
            var recv: String?
            while (true && isOpen) {
                //收发数据过程中移除设备，调用MyApp.ch34xmag.ch34xDriverList.remove(),用信号量防止同时访问
                try {
                    MyApp.ch34xmag1!!.SemDriverList.acquire()
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
                var len = 0
                len = MyApp.ch34xmag1!!.ch34xDriverList[1].ReadData(buffer, 4096)
                if (len > 0) {
                    val msg: Message = Message.obtain()
                    recv = toHexString(buffer, len)
                    msg.obj = recv?.let { getTem(it)?.toInt(16) }!! / 100.0
                    msg.what = 0
                    handler!!.sendMessage(msg)
                }
                MyApp.ch34xmag1!!.SemDriverList.release()
            }
            Log.d("MainActicity", "End readthread")
        }
    }

    //写数据
    inner class writeThread : Thread() {
        override fun run() {
            while (true) {
                Log.d("TAG", "writeThread")
                if (!isOpen) {
                    break
                }
                val To_Send: ByteArray = toByteArray("40 01 01 40 0D")!!
                var ch34xdriver: ch34xMultiDriver
                Log.d("tag", "write" + MyApp.ch34xmag1!!.ch34xDriverList.size)
                Log.d("tag", "write" + MyApp.ch34xmag1!!.ch34xDriverList[1])
                ch34xdriver = MyApp.ch34xmag1!!.ch34xDriverList[1]
                val retval = ch34xdriver.WriteData(To_Send, To_Send.size)
                if (retval < 0) {
                    break
                }
                try {
                    sleep(10000)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }
    }

    /**
     * 将String转化为byte[]数组
     *
     * @param arg 需要转换的String对象
     * @return 转换后的byte[]数组
     */
    private fun toByteArray(arg: String?): ByteArray? {
        if (arg != null) {
            /* 1.先去除String中的' '，然后将String转换为char数组 */
            val NewArray = CharArray(1000)
            val array = arg.toCharArray()
            var length = 0
            for (i in array.indices) {
                if (array[i] != ' ') {
                    NewArray[length] = array[i]
                    length++
                }
            }
            /* 将char数组中的值转成一个实际的十进制数组 */
            val EvenLength = if (length % 2 == 0) length else length + 1
            if (EvenLength != 0) {
                val data = IntArray(EvenLength)
                data[EvenLength - 1] = 0
                for (i in 0 until length) {
                    if (NewArray[i] >= '0' && NewArray[i] <= '9') {
                        data[i] = NewArray[i] - '0'
                    } else if (NewArray[i] >= 'a' && NewArray[i] <= 'f') {
                        data[i] = NewArray[i] - 'a' + 10
                    } else if (NewArray[i] >= 'A' && NewArray[i] <= 'F') {
                        data[i] = NewArray[i] - 'A' + 10
                    }
                }
                /* 将 每个char的值每两个组成一个16进制数据 */
                val byteArray = ByteArray(EvenLength / 2)
                for (i in 0 until EvenLength / 2) {
                    byteArray[i] = (data[i * 2] * 16 + data[i * 2 + 1]).toByte()
                }
                return byteArray
            }
        }
        return byteArrayOf()
    }

    /**
     * 将byte[]数组转化为String类型
     *
     * @param arg    需要转换的byte[]数组
     * @param length 需要转换的数组长度
     * @return 转换后的String队形
     */
    fun toHexString(arg: ByteArray?, length: Int): String? {
        var result = String()
        if (arg != null) {
            for (i in 0 until length) {
                result = (result
                        + (if (Integer.toHexString(
                                if (arg[i] < 0) arg[i] + 256 else arg[i].toInt()
                        ).length == 1
                ) "0"
                        + Integer.toHexString(
                        if (arg[i] < 0) arg[i] + 256 else arg[i].toInt()
                ) else Integer.toHexString(
                        if (arg[i] < 0) arg[i] + 256 else arg[i].toInt()
                )) + " ")
            }
            return result
        }
        return ""
    }

    fun UsbFeatureSupported(): Boolean {
        return packageManager.hasSystemFeature("android.hardware.usb.host")
    }

    //获取温度
    fun getTem(tem: String): String? {
        Log.d("Replace", tem.replace(" ", ""))
        val s = tem.replace(" ", "")
        val s1 = s.substring(10, 12)
        Log.d("s1", s1)
        val s2 = s.substring(8, 10)
        Log.d("s2", s2)
        return s1 + s2
    }

    private fun startVoice() {
        mediaPlayer!!.reset()
        uri = Uri.parse("https://tsn.baidu.com/text2audio?tex=温度正常,即将返回主页面进行访客身份登记&lan=zh&cuid=10.0.19042.1052&ctp=1&tok=24.902233477ec4f5c7a7ae535c3c763813.2592000.1626685339.282335-24368715&audio=3")

        try {
            mediaPlayer!!.setDataSource(applicationContext, uri!!)
            mediaPlayer!!.setAudioStreamType(AudioManager.STREAM_MUSIC)
            mediaPlayer!!.prepareAsync()
            mediaPlayer!!.setOnPreparedListener { mediaPlayer!!.start() }
        } catch (e: IOException) {
            e.printStackTrace()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        isOpen = false
        isConfiged = false
        MyApp.ch34xmag1!!.CloseAll()
    }


}